package com.sun.common;

import lombok.Data;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

@Data
@SuppressWarnings("all")
public class Result<T> implements Serializable{
    private Integer code;//编码 1-成功，0和其他数字为失败
    private String msg;//错误信息
    private T data;//数据


    public static <T> Result<T> success(T data) {
        return new Result<T>(data,CodeMsg.SUCCESS);
    }

    //成功时调用，不需返回数据
    public static <T> Result<T> success() {
        return new Result<T>(CodeMsg.SUCCESS);
    }

    //失败时候的调用，自定义code和msg
    public static <T> Result<T> error(Integer code, String msg) {
        return new Result<T>(code, msg);
    }

    //失败时候的调用，使用CodeMsg中固定的code和msg
    public static <T> Result<T> error(CodeMsg codeMsg) {
        return new Result<T>(codeMsg);
    }

    //失败时候的调用，http的code和自定义的msg
    public static <T> Result<T> error(String msg) {
        CodeMsg codeMsg = new CodeMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
        return new Result<T>(codeMsg);
    }


    private Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private Result(T data, CodeMsg codeMsg) {
        this.data = data;
        if (codeMsg != null) {
            this.code = codeMsg.getCode();
            this.msg = codeMsg.getMsg();
        }
    }
    private Result(CodeMsg codeMsg) {
        if (codeMsg != null) {
            this.code = codeMsg.getCode();
            this.msg = codeMsg.getMsg();
        }
    }
}
